package com.p2p.daily.controller;

import java.math.BigDecimal;
import java.net.PasswordAuthentication;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpClient;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.p2p.account.service.CoinService;
import com.p2p.account.service.GroupsService;
import com.p2p.bill.service.BillService;
import com.p2p.common.base.BaseController;
import com.p2p.common.constants.Message;
import com.p2p.common.enums.ResponseEnum;
import com.p2p.common.redis.vo.RedisVo;
import com.p2p.common.utils.PageUtil;
import com.p2p.common.utils.ParamUtils;
import com.p2p.common.utils.ResMessage;
import com.p2p.common.utils.StringUtils;
import com.p2p.daily.po.P2pDailyOutput;
import com.p2p.daily.service.P2pDailyOutputService;
import com.p2p.daily.vo.P2pMonthOutputData;
import com.p2p.terminal.vo.DailyDataCondition;

@RestController
@RequestMapping(value = "p2pDailyOutput")
public class P2pDailyOutputController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(P2pDailyOutputController.class);
	@Autowired
	private P2pDailyOutputService p2pDailyOutputService;
	@Autowired
	private GroupsService groupsService;
	@Autowired
	private CoinService coinService;
	@Autowired
	private BillService billService;

	/**
	 * 获取日产出
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "selectDailyOutput", method = RequestMethod.POST)
	public ResMessage<P2pDailyOutput> selectDailyData(DailyDataCondition dataCondition) {
		EntityWrapper<P2pDailyOutput> dataWrapper = new EntityWrapper<P2pDailyOutput>();
		String coinType = dataCondition.getCoinType();
		String connectionPool = dataCondition.getConnectionPool();
		String startTime = dataCondition.getStartTime();
		String endTime = dataCondition.getEndTime();
		Integer showZero = dataCondition.getShowZero();
		String poolAddress = dataCondition.getPoolAddress();

		Integer pageIndex = dataCondition.getPageIndex();
		Integer pageSize = dataCondition.getPageSize();
		String sortLineName = dataCondition.getSort();
		String orderType = dataCondition.getOrder();

		if (!("0".equals(coinType)) && !StringUtils.isEmpty(coinType)) {
			dataWrapper.eq("coin_type", coinType);
		}
		if (!("0".equals(connectionPool)) && !StringUtils.isEmpty(coinType)) {
			dataWrapper.eq("wallet_name", connectionPool);
		}
		if (!("0".equals(poolAddress)) && !StringUtils.isEmpty(poolAddress)) {
			dataWrapper.eq("pool_address", poolAddress);
		}
		if (0 == showZero) {
			dataWrapper.ne("coin_count", new java.math.BigDecimal("0.0000000000"));
		}

		dataWrapper.between("date_time", startTime + " 00:00:00", endTime + " 23:00:00");

		Page<P2pDailyOutput> page = null;
		if (StringUtils.isEmpty(sortLineName)) {
			page = new Page<P2pDailyOutput>(pageIndex, pageSize);
		} else {
			page = new Page<P2pDailyOutput>(pageIndex, pageSize, sortLineName);
			page.setAsc(PageUtil.isAsc(orderType));
		}

		page = p2pDailyOutputService.selectPage(page, dataWrapper);
		List<P2pDailyOutput> originalData = page.getRecords();

		return new ResMessage<>(originalData, ResponseEnum.SUCCESS.getMsg(), true, page.getTotal());

	}

	/**
	 * 更新日产出
	 *
	 * @param request
	 * @return
	 */

	@RequestMapping(value = "updateP2pDailyOutput", method = RequestMethod.GET)
	public Message updateP2pDailyOutput(HttpServletRequest request) {
		String id = ParamUtils.getParameter(request, "id");
		String coinCount = ParamUtils.getParameter(request, "coinCount");
		String coinPrice = ParamUtils.getParameter(request, "coinPrice");
		String confirmIncome = ParamUtils.getParameter(request, "confirmIncome");
		P2pDailyOutput p2pDailyOutput = new P2pDailyOutput();
		p2pDailyOutput.setStatus(1);
		p2pDailyOutput.setId(Long.parseLong(id));
		p2pDailyOutput.setCoinCount(new BigDecimal(coinCount));
		p2pDailyOutput.setDayPrice(new BigDecimal(coinPrice));
		p2pDailyOutput.setPredictIncome(new BigDecimal(confirmIncome));
		p2pDailyOutput.setUpdateTime(new Date());

		boolean flagUpdate = p2pDailyOutputService.updateById(p2pDailyOutput);
		// 更新发布账单
		EntityWrapper<P2pDailyOutput> dataWrapper = new EntityWrapper<P2pDailyOutput>();
		dataWrapper.eq("id", Long.parseLong(id));
		P2pDailyOutput OutputBill = p2pDailyOutputService.selectOne(dataWrapper);
		billService.updateBill(OutputBill);
		if (flagUpdate) {
			return new Message(200, "更新成功");

		}
		return new Message(500, "更新失败");
	}

	/**
	 * 更新日产出价格
	 *
	 * @param request
	 * @return
	 */

	@RequestMapping(value = "updateP2pDailyOutputPrice", method = RequestMethod.GET)
	public Message updateP2pDailyOutputPrice(HttpServletRequest request) {
		String id = ParamUtils.getParameter(request, "id");
		String coinCount = ParamUtils.getParameter(request, "coinCount");
		String coinType = ParamUtils.getParameter(request, "coinType");
		
		String price = getPrice(coinType);
		
		P2pDailyOutput p2pDailyOutput = new P2pDailyOutput();
		p2pDailyOutput.setId(Long.parseLong(id));
		p2pDailyOutput.setDayPrice(new BigDecimal(price));
		p2pDailyOutput.setPredictIncome(new BigDecimal(price).multiply(new BigDecimal(coinCount)));
		p2pDailyOutput.setUpdateTime(new Date());

		boolean flagUpdate = p2pDailyOutputService.updateById(p2pDailyOutput);
		

		if (flagUpdate) {
			return new Message(200, "更新成功",p2pDailyOutput);

		}
		return new Message(500, "更新失败");
	}

	/**
	 * 获取月产出
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "selectMonthOutput", method = RequestMethod.POST)
	public ResMessage<P2pMonthOutputData> selectMonthOutput(DailyDataCondition dataCondition) {
		String coinType = dataCondition.getCoinType();
		String connectionPool = dataCondition.getConnectionPool();
		String startTime = dataCondition.getStartTime();
		Integer showZero = dataCondition.getShowZero();
		String poolAddress = dataCondition.getPoolAddress();

		Integer pageIndex = dataCondition.getPageIndex();
		Integer pageSize = dataCondition.getPageSize();

		if (("0".equals(coinType)) || StringUtils.isEmpty(coinType)) {
			coinType = null;
		}
		if (("0".equals(connectionPool)) || StringUtils.isEmpty(connectionPool)) {
			connectionPool = null;
		}
		if (("0".equals(poolAddress)) || StringUtils.isEmpty(poolAddress)) {
			poolAddress = null;
		}

		List<P2pMonthOutputData> selectMonthDataList = p2pDailyOutputService.selectMonthDataList(coinType,
				connectionPool, startTime, showZero, poolAddress, pageSize, (pageIndex - 1) * pageSize);
		Integer size = p2pDailyOutputService.selectMonthDataSize(coinType, connectionPool, startTime, showZero,
				poolAddress);
		Integer dateCount = p2pDailyOutputService.selectMonthCalculateDataCount(coinType, connectionPool, startTime,
				showZero, poolAddress);
		selectMonthDataList.forEach(itme -> {
			itme.setDayCount(dateCount);
			BigDecimal dayPrice = itme.getDayPrice();
			BigDecimal averagePrice = dayPrice.divide(new BigDecimal(dateCount), 10, BigDecimal.ROUND_HALF_EVEN);
			itme.setDayPrice(averagePrice);
			itme.setDateTime(startTime);
		});

		return new ResMessage<>(selectMonthDataList, ResponseEnum.SUCCESS.getMsg(), true, size);

	}

	public String getPrice(String coinType) {

		try {

			HttpClient client = new HttpClient();
			NodeFilter filter = new TagNameFilter("a");

			Parser parser = new Parser("https://coinmarketcap.com/");
			client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
			parser.setEncoding("utf-8");

			NodeList nodeList = parser.parse(filter);
			String str1[] = nodeList.asString().split("\n");
			
			for (int i = 0; i < str1.length; i++) {
				if (str1[i].indexOf("$") > -1) {
					if (str1[i].substring(0, 3).equals(coinType)) {
						int location = str1[i].indexOf("$");
						String price = str1[i].substring(location + 1, str1[i].indexOf("$", (location + 1)));
						return price;
					}
				}

			}

			

		} catch (ParserException ex) {
			ex.printStackTrace();
			return "0";
		}
		return "0";
	}
}
